package com.example.mydy;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;

import com.example.mydy.adapter.AchievementAdapter;
import com.example.mydy.manager.AchievementManager;
import com.example.mydy.model.Achievement;
import com.example.mydy.utils.MockDataManager;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;

import java.util.ArrayList;
import java.util.List;

/**
 * 成就页面活动
 */
public class AchievementsActivity extends AppCompatActivity {

    private ViewPager2 viewPager;
    private TabLayout tabLayout;
    private TextView tvAchievementSummary;
    private ProgressBar progressAchievements;
    private AchievementManager achievementManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        try {
            setContentView(R.layout.activity_achievements);
            
            Log.d("AchievementsActivity", "onCreate: 设置内容视图完成");

            // 初始化AchievementManager
            achievementManager = AchievementManager.getInstance(this);
            Log.d("AchievementsActivity", "onCreate: 初始化AchievementManager完成");

            // 初始化工具栏
            Toolbar toolbar = findViewById(R.id.toolbar);
            setSupportActionBar(toolbar);
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            toolbar.setNavigationOnClickListener(v -> onBackPressed());
            Log.d("AchievementsActivity", "onCreate: 初始化工具栏完成");

            // 初始化视图
            viewPager = findViewById(R.id.view_pager);
            tabLayout = findViewById(R.id.tabs);
            tvAchievementSummary = findViewById(R.id.tv_unlock_count);
            progressAchievements = findViewById(R.id.progress_achievements);
            Log.d("AchievementsActivity", "onCreate: 初始化视图完成");

            // 设置ViewPager和TabLayout
            setupViewPager();
            Log.d("AchievementsActivity", "onCreate: 设置ViewPager完成");

            // 加载成就数据
            loadAchievements();
            Log.d("AchievementsActivity", "onCreate: 加载成就数据完成");
        } catch (Exception e) {
            Log.e("AchievementsActivity", "onCreate出现异常: " + e.getMessage(), e);
            Toast.makeText(this, "初始化出错: " + e.getMessage(), Toast.LENGTH_LONG).show();
            finish(); // 无法初始化，退出Activity
        }
    }

    /**
     * 设置ViewPager和TabLayout
     */
    private void setupViewPager() {
        try {
            // 创建ViewPager适配器
            AchievementPagerAdapter pagerAdapter = new AchievementPagerAdapter(this);
            viewPager.setAdapter(pagerAdapter);
            Log.d("AchievementsActivity", "setupViewPager: 设置适配器完成");

            // 将TabLayout与ViewPager关联
            new TabLayoutMediator(tabLayout, viewPager, (tab, position) -> {
                switch (position) {
                    case 0:
                        tab.setText("全部");
                        break;
                    case 1:
                        tab.setText("登录");
                        break;
                    case 2:
                        tab.setText("任务");
                        break;
                    case 3:
                        tab.setText("社交");
                        break;
                    case 4:
                        tab.setText("收益");
                        break;
                }
            }).attach();
            Log.d("AchievementsActivity", "setupViewPager: TabLayoutMediator设置完成");
        } catch (Exception e) {
            Log.e("AchievementsActivity", "setupViewPager出现异常: " + e.getMessage(), e);
            Toast.makeText(this, "设置视图出错: " + e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }

    /**
     * 加载成就数据
     */
    private void loadAchievements() {
        try {
            // 获取当前用户名
            String username = MockDataManager.getCurrentUsernameStatic();
            if (username == null) {
                Log.w("AchievementsActivity", "loadAchievements: 用户名为空");
                Toast.makeText(this, "未获取到用户信息", Toast.LENGTH_SHORT).show();
                return;
            }
            Log.d("AchievementsActivity", "loadAchievements: 当前用户名 = " + username);

            // 检查用户成就
            achievementManager.checkAllAchievements(username);
            Log.d("AchievementsActivity", "loadAchievements: 成就检查完成");

            // 更新成就总结
            int unlockedCount = achievementManager.getUnlockedAchievementsCount();
            int totalCount = achievementManager.getTotalAchievementsCount();
            int progressPercent = totalCount > 0 ? (unlockedCount * 100 / totalCount) : 0;
            Log.d("AchievementsActivity", "loadAchievements: 解锁成就 = " + unlockedCount + ", 总成就 = " + totalCount);

            tvAchievementSummary.setText(String.format("成就完成进度 %d/%d", unlockedCount, totalCount));
            progressAchievements.setProgress(progressPercent);
            Log.d("AchievementsActivity", "loadAchievements: 界面更新完成");
        } catch (Exception e) {
            Log.e("AchievementsActivity", "loadAchievements出现异常: " + e.getMessage(), e);
            Toast.makeText(this, "加载成就数据出错: " + e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }

    /**
     * ViewPager适配器
     */
    private static class AchievementPagerAdapter extends FragmentStateAdapter {

        public AchievementPagerAdapter(@NonNull FragmentActivity fragmentActivity) {
            super(fragmentActivity);
        }

        @NonNull
        @Override
        public Fragment createFragment(int position) {
            // 根据位置返回不同类型的成就列表Fragment
            switch (position) {
                case 0:
                    return AchievementListFragment.newInstance(Achievement.TYPE_ALL); // 全部
                case 1:
                    return AchievementListFragment.newInstance(Achievement.TYPE_LOGIN); // 登录
                case 2:
                    return AchievementListFragment.newInstance(Achievement.TYPE_TASK); // 任务
                case 3:
                    return AchievementListFragment.newInstance(Achievement.TYPE_SOCIAL); // 社交
                case 4:
                    return AchievementListFragment.newInstance(Achievement.TYPE_INCOME); // 收益
                default:
                    return AchievementListFragment.newInstance(Achievement.TYPE_ALL);
            }
        }

        @Override
        public int getItemCount() {
            return 5; // 5个标签页
        }
    }

    /**
     * 成就列表Fragment
     */
    public static class AchievementListFragment extends Fragment {
        private static final String ARG_ACHIEVEMENT_TYPE = "achievement_type";
        private int achievementType;
        private List<Achievement> achievements;
        private RecyclerView recyclerView;
        private LinearLayout tvEmptyView;
        private ProgressBar progressBar;
        private AchievementManager achievementManager;

        /**
         * 创建Fragment实例
         */
        public static AchievementListFragment newInstance(int achievementType) {
            AchievementListFragment fragment = new AchievementListFragment();
            Bundle args = new Bundle();
            args.putInt(ARG_ACHIEVEMENT_TYPE, achievementType);
            fragment.setArguments(args);
            return fragment;
        }

        @Override
        public void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            if (getArguments() != null) {
                achievementType = getArguments().getInt(ARG_ACHIEVEMENT_TYPE, Achievement.TYPE_ALL);
            }
            achievementManager = AchievementManager.getInstance(requireContext());
        }

        @Nullable
        @Override
        public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
            View view = inflater.inflate(R.layout.fragment_achievement_list, container, false);
            recyclerView = view.findViewById(R.id.recycler_view);
            tvEmptyView = view.findViewById(R.id.empty_view);
            progressBar = view.findViewById(R.id.progress_bar);

            // 设置RecyclerView
            recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
            
            return view;
        }
        
        @Override
        public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
            super.onViewCreated(view, savedInstanceState);
            try {
                // 显示加载中
                progressBar.setVisibility(View.VISIBLE);
                recyclerView.setVisibility(View.GONE);
                tvEmptyView.setVisibility(View.GONE);
                
                // 加载成就数据
                loadAchievements();
            } catch (Exception e) {
                Log.e("AchievementListFragment", "onViewCreated出现异常: " + e.getMessage(), e);
                Toast.makeText(getContext(), "加载成就数据出错: " + e.getMessage(), Toast.LENGTH_LONG).show();
            }
        }
        
        /**
         * 加载成就数据
         */
        private void loadAchievements() {
            try {
                // 根据类型获取成就
                achievements = achievementManager.getAchievementsByType(achievementType);
                
                // 更新UI
                if (achievements.isEmpty()) {
                    recyclerView.setVisibility(View.GONE);
                    tvEmptyView.setVisibility(View.VISIBLE);
                } else {
                    // 设置适配器
                    AchievementAdapter adapter = new AchievementAdapter(requireContext(), achievements);
                    recyclerView.setAdapter(adapter);
                    recyclerView.setVisibility(View.VISIBLE);
                    tvEmptyView.setVisibility(View.GONE);
                }
                
                // 隐藏进度条
                if (progressBar != null) {
                    progressBar.setVisibility(View.GONE);
                }
                
                Log.d("AchievementListFragment", "成就数据加载完成, 类型: " + achievementType + ", 数量: " + achievements.size());
            } catch (Exception e) {
                Log.e("AchievementListFragment", "loadAchievements出现异常: " + e.getMessage(), e);
                if (getContext() != null) {
                    Toast.makeText(getContext(), "加载成就列表出错: " + e.getMessage(), Toast.LENGTH_LONG).show();
                }
                
                // 出错时也隐藏进度条
                if (progressBar != null) {
                    progressBar.setVisibility(View.GONE);
                }
            }
        }
    }
}